package org.example.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.example.mapper.UserMapper;
import org.example.pojo.PageBean;
import org.example.pojo.User;
import org.example.pojo.VulnScanTask;
import org.example.service.UserService;
import org.example.utils.Jwt;
import org.example.utils.Loggable;
import org.example.utils.Result;
import org.example.utils.TokenBlacklistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Loggable(action = "获取用户列表")
    @GetMapping("/list")
    public Result userList(@RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer size) {
        PageHelper.startPage(page, size);
        List<User> users = userMapper.userList();
        Page<User> p = (Page<User>) users;
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return Result.success(pageBean);
    }
    @Loggable(action = "登录")
    @PostMapping("/login")
    public Result userLogin(@RequestBody User user) {
        Map<String, Object> obj = new HashMap<>();
        Map<String, Object> data = new HashMap<>();

            List<User> users = userService.userLogin(user);
            if (!users.isEmpty()) {
//                Map<String, Object> obj = new HashMap<>();
                obj.put("username",user.getUsername());
                obj.put("password",user.getPassword());
                String token = Jwt.generateJwt(obj);
//                Map<String, Object> data = new HashMap<>();
                data.put("user_id", users.get(0).getId());
                data.put("username",user.getUsername());
                data.put("role",users.get(0).getRole());
                data.put("token",token);
                Date currentDate = new Date();
                // 定义日期时间的格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedDate = sdf.format(currentDate);
                user.setLastLoginAt(formattedDate);
                userMapper.setLoginTime(user);
                return Result.success("登录成功", data);
            } else {
                if (Objects.equals(user.getUsername(), "admin") && Objects.equals(user.getPassword(), "admin123")) {
                    obj.put("username",user.getUsername());
                    obj.put("password",user.getPassword());
                    String token = Jwt.generateJwt(obj);
                    user.setLocked(1);
                    user.setRole("默认管理员");
                    userMapper.userRegister(user);
                    data.put("user_id", user.getId());
                    data.put("username",user.getUsername());
                    data.put("role","默认管理员");
                    data.put("token",token);
                    user.setLastLoginAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    userMapper.setLoginTime(user);
                    return Result.success("登录成功", data);
                }
            }
        return Result.error("用户名或密码错误");
    }
    @Loggable(action = "添加/注册用户")
    @PostMapping("/register")
    public Result userRegister(@RequestBody User user) {
        return userService.userRegister(user);
    }
    @Loggable(action = "退出登录")
    @PostMapping("/logout")
    public Result logout(@RequestHeader("Authorization") String token) {
            if (token != null) {
                TokenBlacklistService.addToBlacklist(token);
            }
            return Result.success();
    }
    @Loggable(action = "获取用户信息")
    @GetMapping("/info/{userId}")
    public Result userInfo(@PathVariable("userId") Integer userId) {
        User user = userMapper.getUserById(userId);
        return Result.success(user);
    }
    @Loggable(action = "修改用户信息")
    @PutMapping("/info")
    public Result updateInfo(@RequestBody User user) {
        userMapper.updateInfo(user);
        return Result.success();
    }
    @Loggable(action = "删除用户")
    @DeleteMapping("/user/{id}")
    public Result delUser(@PathVariable Integer id) {
        userMapper.delUser(id);
        return Result.success();
    }
}
